package ads_config

import (
	"gorm.io/gorm"
	"server/global"
	"server/model/common/request"
)

type AdsConfigService struct {
}

func (adsConfigService *AdsConfigService) CreateAdsConfig(adsConfig *AdsConfig) (err error) {
	err = global.SysDB.Create(adsConfig).Error
	return err
}

func (adsConfigService *AdsConfigService) DeleteAdsConfig(adsConfig AdsConfig) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&AdsConfig{}).Where("id = ?", adsConfig.ID).Update("deleted_by", adsConfig.DeletedBy).Error; err != nil {
			return err
		}
		if err = tx.Delete(&adsConfig).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}

func (adsConfigService *AdsConfigService) DeleteAdsConfigByIds(ids request.IdsReq, deleted_by uint) (err error) {
	err = global.SysDB.Transaction(func(tx *gorm.DB) error {
		if err := tx.Model(&AdsConfig{}).Where("id in ?", ids.Ids).Update("deleted_by", deleted_by).Error; err != nil {
			return err
		}
		if err := tx.Where("id in ?", ids.Ids).Delete(&AdsConfig{}).Error; err != nil {
			return err
		}
		return nil
	})
	return err
}

func (adsConfigService *AdsConfigService) UpdateAdsConfig(adsConfig AdsConfig) (err error) {
	err = global.SysDB.Save(&adsConfig).Error
	return err
}

func (adsConfigService *AdsConfigService) GetAdsConfigById(id uint) (adsConfig AdsConfig, err error) {
	err = global.SysDB.Where("id = ?", id).First(&adsConfig).Error
	return
}

func (adsConfigService *AdsConfigService) GetAdsConfigInfoList(info AdsConfigSearch) (list []AdsConfig, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	db := global.SysDB.Model(&AdsConfig{})
	var adsConfigs []AdsConfig
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	err = db.Limit(limit).Offset(offset).Find(&adsConfigs).Error
	return adsConfigs, total, err
}

func (adsConfigService *AdsConfigService) GetAllAdsConfigs() (adsConfig []AdsConfig, err error) {
	err = global.SysDB.Find(&adsConfig).Error
	return adsConfig, err
}

func (adsConfigService *AdsConfigService) GetAdsConfig() (adsConfig []AdsConfig, err error) {
	err = global.SysDB.Find(&adsConfig).Error
	return adsConfig, err
}
